package com.fecean.aabbc.commons.exception;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 自定义异常
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2019-12-06 14:55
 * @blame Team
 */
public class EasyException extends RuntimeException implements IException {

    private static final long serialVersionUID = -4682832496873078898L;

    private static final String DEFAULT_CODE = "99999";
    private static final String DEFAULT_MESSAGE = "系统出错";
    /**
     * 异常编码
     */
    private String code;

    private EasyException(){
        super();
        this.code = DEFAULT_CODE;
    }

    private EasyException(String message){
        super(message);
        this.code = DEFAULT_CODE;
    }

    private EasyException(String code, String message){
        super(message);
        this.code = code;
    }

    private EasyException(Throwable cause){
        super(cause);
        this.code = DEFAULT_CODE;
    }

    private EasyException(String code, Throwable cause){
        super(cause);
        this.code = code;
    }

    public static EasyException of(String message){
        return new EasyException(message);
    }

    public static EasyException of(String code, String message){
        return new EasyException(code, message);
    }

    public static EasyException of(Throwable cause){
        return new EasyException(cause);
    }

    public static EasyException of(String code, Throwable cause){
        return new EasyException(code, cause);
    }

    @Override
    public String getCode(){
        return code;
    }

    @Override
    public String getMessage(){
        return super.getMessage() == null ? DEFAULT_MESSAGE : super.getMessage();
    }

    @Override
    public String getTrace() {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        this.printStackTrace(pw);
        return sw.getBuffer().toString();
    }
}
